var page;//完工列表的页码
var _index = -1;//完工表的下标（用于表勾选）
var rowIndex = "%^%%%%";//完工表的下标（用于改变选中行样式）
var flag = false;//区分状态
var input_name = ["工序","良品","工废","料废","工废1","返修","次品","备注"];
var input_namet = ["工序","良品","工废","料废","工废1","返修","次品","备注"];
var input_id = ["fOper","fPassQty","fScrapQty","fForitemQty","fScrapNotMeQty","fReworkQty","fOthQty","fNote"];
var input_ids = ["fOper","fPassQty","fScrapQty","fForitemQty","fScrapNotMeQty","fReworkQty","fOthQty","fNote"];
var input_idss = ["fOper","fPassQty","fScrapQty","fForitemQty","fScrapNotMeQty","fReworkQty","fOthQty"];
//fRestructQty
var input_sum = -1;
var fIsMerge = 0;//表示是否是合并工序,1--合并，0--不合并
var fDisPathId;
var fStartWorkId;

// 刷新表格时，保存当前所在页面
var currentPageNumber;
/*
 * @Description: 预加载
 * @param : 
 */
$(function() {
	resizeIframeHight();
	initFinishTable();
	pullDown();
	
	//点击Tab刷新表格
	$(".FO",parent.document).click(function(){
		$('#finishTable').bootstrapTable('refresh');
//		setTimeout(function(){
//			if(_index != -1){
//				$('#stratTable').bootstrapTable('check',_index);
//			}
//		},500);
	});
});

/** 
 * @description: 初始化开工记录表 
 * @param :  
 */
function initFinishTable() {
	$('#finishTable').bootstrapTable('destroy').bootstrapTable({
		url : pathUrl("start/findByCondition.action"),//请求后台的URL
		height : $(window).height()*0.73,//行高
		method : "POST",//请求方式
		//striped : true,//是否显示行间隔色
		cache : false,//是否使用缓存，默认为true
		pagination : true,//是否显示分页
		clickToSelect : true,//是否启用点击选中行
		singleSelect : true,//是否单选
		pageNumber : 1,//初始化加载第几页
		pageSize : 10,//每页的记录行数
		sidePagination : "server", // 分页方式：client客户端分页，server服务端分页（*）
		pageList : [ 10, 25, 50, 100, 'ALL' ],// 分页方式：client客户端分页，server服务端分页
		rowStyle : function(row, index) {//自定义样式，参数为：row：行数据，index：行下标
			var classes = [ 'success' ];
			if (index == rowIndex) {
				return {
					classes : classes[0]
				};
			}
			return {};
		},
		queryParams : function(params) {//传递参数
			var data= {},orderBy = params.sort + " " + params.order;      //排序列名;
			data.offset = params.offset;
			data.row = params.limit;
			if(params.sort==undefined){
				orderBy = "fDate" + " " + params.order;
			}
			data.fBillNo = $("#fBillNo").val();
			data.fWorker = $("#fWorkerF").val();
			data.fCode = $("#fCode").val();
			data.fDepId = $("#fDepId").val();
			data.orderBy = orderBy;//排序：要排序字段 + 排序规则
			return data;
		},
		dataType : 'JSON',//数据类型
		uniqueId : "id",//每一行的唯一标识，一般为主键列
		columns : [/* {
			checkbox : true
		}, */{
			field : "fBillNo",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '任务单号'
		}, {
			field : "fCode",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '派工单号'
		}, {
			field : "fNumber",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '产品代码'
		}, {
			field : "fName",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '产品名称'
		}, {
			field : "fModel",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '规格型号'
		}, {
			field : "fOperSN",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '工序号'
		}, {
			field : "fOper",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '工序名称',
			formatter : formatterStringShort
		}, {
			field : "fQcStatus",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '首检',
			formatter : function(value,row,index){
				if(row.fQcStatus > 1){
					return "是";
				}else if(row.fQcStatus <= 1){
					return "否";
				}
			}
		}, {
			field : "fNote",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '加工说明',
			formatter : formatterStringLong
		}, {
			field : "fMachine",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '设备名称'
		}, {
			field : "fTargetQty1",
			align : 'left',
			valign: 'middle',
//			sortable : true,
			title : '派工数量',
			formatter : function(value,row,index){
				return parseFloat(row.fTargetQty) - parseFloat(row.fQty);
			}
		}, {
			field : "fWorkerName",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '操作工'
		},  {
			field : "fDate",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '开工时间',
			formatter : function(value,row,index){
				return timeFormatter(row.fDate);
			}
		}],
		onClickRow : function(row, $element) {//行单击
			$('.success').removeClass('success');// 去除之前选中的行的，选中样式
			$($element).addClass('success');// 添加当前选中的 success样式用于区别
			index = $element.data('index');
			rowIndex = index;
			page = $('.pagination .active').find("a").eq(0).text();
			$("#content_bottom_single").css("display","none");
			$("#contentId").html("");
			$("#contentId_single").html("");
			console.log(row);
			var fNumberSub = row.fNumber.substr(0,2);			
			if(fNumberSub == "04" || (fNumberSub == "99" && row.fNumber.substr(3,2) != "WY")){
				if(row.fQcStatus <= 1){
					// swal_Tips("该条记录还未进行首检！");
					showSwal('挂起', '该条记录未首检，不能报工！如需进行挂起操作，请点击挂起', '挂起', function(result) {
						if (result.value) {
							// TODO:添加挂起操作事件
							showLoading();
							$.ajax({
								url : pathUrl("end/suspending.action"),
								type : "POST",
								dataType : "JSON",
								data : {
									fDisId : row.fDisPathId,
									fStartWorkId: row.id,
								},
								success : function(data) {
									if(data.code == "0000"){
										swal_Tips_Short(data.message);
										$('#finishTable').bootstrapTable('refresh');
									}else{
										swal_Tips(data.message);
									}
								},
								error : function(request) {
									swal_Tips_Error();
								}
							});
						}
					});
					return;
				}	
			}		
			fDisPathId = row.fDisPathId;
			fStartWorkId = row.id;
			loadingCustom('正在加载中。。。');
			if(row.fIsMerge == 1){
				fIsMerge = 1;
				$.ajax({
					url : pathUrl("start/findByMergeOper.action"),
					type : "POST",
					dataType : "JSON",
					data : {
						fQty : row.fTargetQty,
						id : row.id
					},
					success : function(data) {
//						console.log(data);
						input_sum = data.length;
						$("#modal-body-id").css("height",data.length * 40 + 45);						
						if(data.length  > 0){
							//循环生产form表单
							var hl = "";
							for(var i = 0; i < data.length; i++){
								var temp = data[i];	
								hl += "<span id = 'fOperSN" + i + "'style = 'display:none;'>" + temp.fOperSN + "</span><span id = 'fMergeCode" + i + "'style = 'display:none;'>" + temp.fMergeCode + "</span>";
								hl += "<span id = 'fCardId" + i + "'style = 'display:none;'>" + temp.fCardId + "</span>";
								for(var j = 0; j < input_id.length; j++){
									hl += "<div class='col-sm-2 col-md-2 bottomContent' style='width: 12%; padding:0px 0px 3px 0px;'><span class='bottomSpan'>";								
	                                if(j == 1){
										hl += "<span class='requiredCss'>*</span>" + input_name[j] + ":";
									}else{
										hl += input_name[j] + ":";
									}
									hl += "</span>";
									var valu = temp[input_id[j]];
									if(valu == null){
										valu = 0;
									}
									if(j == 0){
										hl += "<input type='text' id='" + input_id[j] + i +"' readonly = 'true' value = '" + valu + "'";
									}else if(j == 1){//当数量为良品数的时候	
										var t = parseFloat(row.fTargetQty) - parseFloat(row.fQty);
										hl += "<input type='text' id='" + input_id[j] + i +"'value = '" + t +"'";	
									}else{
										hl += "<input type='text' id='" + input_id[j] + i +"'value = '" + valu +"'";
									}								
									hl += " name='" + input_id[j] + "' class='clean-c form-control bj_color' autocomplete='off' onkeyup= changeVal(this) onafterpaste='if(isNaN(value))execCommand(&apos;undo&apos;)'/>";															
									hl += "</div>";
								}														
							}
							$("#contentId").html(hl);
							$("#content_bottom").css("display","block");
							$('#fPassQty0').focus();//良品数输入框获得焦点							
							$("#mergeModal").modal('show');							
						}else{
							input_sum = 1;
							var hl = "";
							for(var i = 0; i < input_name.length; i++){	
								hl += "<div class='col-sm-2 col-md-2 bottomContent' style='width: 13%; padding:0px 0px 3px 0px;'><span class='bottomSpan'>";								
			                    if(i == 1){
									hl += "<span class='requiredCss'>*</span>" + input_name[i] + ":";
								}else{
									hl += input_name[i] + ":";
								}
								hl += "</span>";
								if(i == 0){
									hl += "<input type='text' id='" + input_id[i] + 0 +"' readonly = 'true'";
								}else{
									hl += "<input type='text' id='" + input_id[i] + 0 +"'";	
								}								
								hl += " name='" + input_id[i] + "' class='clean-c form-control bj_color' autocomplete='off' onkeyup='if(isNaN(value))execCommand(&apos;undo&apos;)' onafterpaste='if(isNaN(value))execCommand(&apos;undo&apos;)'/>";															
								hl += "</div>";
							}
							$("#contentId_single").html(hl);
							$("#fPassQty0").val(parseFloat(row.fTargetQty) - parseFloat(row.fQty));//给良品数赋值	
							$("#fOper0").val(row.fOper);//给良品数赋值	
							$('#fPassQty0').focus();//良品数输入框获得焦点
							$("#content_bottom_single").css("display","block");
						}
						swal.close();//关闭sweetAlert2提示框
					},
					error : function(request) {
						swal_Tips_Error();
					}
				});
			}else{
				fIsMerge = 0;
				input_sum = 1;
				var hl = "";
				for(var i = 0; i < input_namet.length; i++){	
					hl += "<div class='col-sm-2 col-md-2 bottomContent' style='width: 13%; padding:0px 0px 3px 0px;'><span class='bottomSpan'>";								
                    if(i == 1){
						hl += "<span class='requiredCss'>*</span>" + input_namet[i] + ":";
					}else{
						hl += input_namet[i] + ":";
					}
					hl += "</span>";
					if(i == 0){
						hl += "<input type='text' id='" + input_ids[i] + 0 +"' readonly = 'true'";
					}else{
						hl += "<input type='text' id='" + input_ids[i] + 0 +"'";	
					}								
    //				hl += " name='" + input_ids[i] + "' class='clean-c form-control bj_color' autocomplete='off' onkeyup='if(isNaN(value))execCommand(&apos;undo&apos;)' onafterpaste='if(isNaN(value))execCommand(&apos;undo&apos;)'/>";
					hl += " name='" + input_ids[i] + "' class='clean-c form-control bj_color' autocomplete='off'  />";
					hl += "</div>";
				}
				$("#contentId_single").html(hl);
				swal.close();//关闭sweetAlert2提示框
				$("#fPassQty0").val(parseFloat(row.fTargetQty) - parseFloat(row.fQty));//给良品数赋值	
				$("#fOper0").val(row.fOper);//给良品数赋值	
				$('#fPassQty0').focus();//良品数输入框获得焦点
				$("#content_bottom_single").css("display","block");
			}							
			$("#fWorker").val(row.fWorker);//获取操作工ID
			$("#fStartWorkId").val(row.id);//获取开工表ID
			$("#fTargetQty").val(parseFloat(row.fTargetQty) - parseFloat(row.fQty));//获取派工数
//			$("#fPassQty").val(parseFloat(row.fTargetQty) - parseFloat(row.fQty));//给良品数赋值			
//			$('#fPassQty0').focus();//良品数输入框获得焦点
		},
		onPageChange : function(number, size) {//翻页
			if (page == number) {
				rowIndex = index;
			} else {
				$('.success').removeClass('success');
				rowIndex = "%^%%%%";
			}
		},
		onUncheck : function(index){//取消勾选
			$("#fWorker,#fStartWorkId,#fTargetQty").val("");//清空操作工ID、开工表ID、派工数
			$('#fPassQty').blur();//良品数输入框失去焦点
			$('.success').removeClass('success');
			rowIndex = "%^%%%%";
		}
	});
}

/** 
 * @description: 刷新表格时，重新初始化开工记录表并停留在当前页 
 * @param :  
 */
function initFinishTableAtCurrentPage(currentPageNumber) {
	$('#finishTable').bootstrapTable('destroy').bootstrapTable({
		// 请求后台的URL
		url : pathUrl("start/findByCondition.action"),
		// 行高
		height : $(window).height()*0.73,
		// 请求方式
		method : "POST",
		// 是否显示行间隔色
		//striped : true,
		// 是否使用缓存，默认为true
		cache : false,
		// 是否显示分页
		pagination : true,
		// 是否启用点击选中行
		clickToSelect : true,
		// 是否单选
		singleSelect : true,
		// 初始化加载第几页
		pageNumber : currentPageNumber,
		// 每页的记录行数
		pageSize : 10,
		// 分页方式：client客户端分页，server服务端分页（*）
		sidePagination : "server", 
		// 每页行数选项
		pageList : [ 10, 25, 50, 100, 'ALL' ],
		// 自定义样式，参数为：row：行数据，index：行下标
		rowStyle : function(row, index) {
			var classes = [ 'success' ];
			if (index == rowIndex) {
				return {
					classes : classes[0]
				};
			}
			return {};
		},
		// 传递参数
		queryParams : function(params) {
			// 排序列名
			var data= {},orderBy = params.sort + " " + params.order;      
			data.offset = params.offset;
			data.row = params.limit;
			if(params.sort==undefined){
				orderBy = "fDate" + " " + params.order;
			}
			data.fBillNo = $("#fBillNo").val();
			data.fWorker = $("#fWorkerF").val();
			data.fCode = $("#fCode").val();
			data.fDepId = $("#fDepId").val();

			// 排序：要排序字段 + 排序规则
			data.orderBy = orderBy;
			return data;
		},
		// 数据类型
		dataType : 'JSON',
		// 每一行的唯一标识，一般为主键列
		uniqueId : "id",
		columns : [/* {
			checkbox : true
		}, */{
			field : "fBillNo",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '任务单号'
		}, {
			field : "fCode",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '派工单号'
		}, {
			field : "fNumber",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '产品代码'
		}, {
			field : "fName",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '产品名称'
		}, {
			field : "fModel",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '规格型号'
		}, {
			field : "fOperSN",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '工序号'
		}, {
			field : "fOper",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '工序名称',
			formatter : formatterStringShort
		}, {
			field : "fQcStatus",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '首检',
			formatter : function(value,row,index){
				if(row.fQcStatus > 1){
					return "是";
				}else if(row.fQcStatus <= 1){
					return "否";
				}
			}
		}, {
			field : "fNote",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '加工说明',
			formatter : formatterStringLong
		}, {
			field : "fMachine",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '设备名称'
		}, {
			field : "fTargetQty1",
			align : 'left',
			valign: 'middle',
//			sortable : true,
			title : '派工数量',
			formatter : function(value,row,index){
				return parseFloat(row.fTargetQty) - parseFloat(row.fQty);
			}
		}, {
			field : "fWorkerName",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '操作工'
		},  {
			field : "fDate",
			align : 'left',
			valign: 'middle',
			sortable : true,
			title : '开工时间',
			formatter : function(value,row,index){
				return timeFormatter(row.fDate);
			}
		}],
		// 行单击
		onClickRow : function(row, $element) {
			// 去除之前选中的行的，选中样式
			$('.success').removeClass('success');

			// 添加当前选中的 success样式用于区别
			$($element).addClass('success');
			currentPageNumber = $('#finishTable').bootstrapTable('getOptions').pageNumber;
			index = $element.data('index');
			rowIndex = index;
			page = $('.pagination .active').find("a").eq(0).text();
			$("#content_bottom_single").css("display","none");
			$("#contentId").html("");
			$("#contentId_single").html("");
			console.log(row);
			var fNumberSub = row.fNumber.substr(0,2);			
			if(fNumberSub == "04" || (fNumberSub == "99" && row.fNumber.substr(3,2) != "WY")){
				if(row.fQcStatus <= 1){
					// swal_Tips("该条记录还未进行首检！");
					showSwal('挂起', '该条记录未首检，不能报工！如需进行挂起操作，点击挂起', '挂起', function(result) {
						if (result.value) {
							// TODO:添加挂起操作事件
							showLoading();
							$.ajax({
								url : pathUrl("end/suspending.action"),
								type : "POST",
								dataType : "JSON",
								data : {
									fDisId : row.fDisPathId,
									fStartWorkId: row.id,
								},
								success : function(data) {
									if(data.code == "0000"){
										swal_Tips_Short(data.message);
										initFinishTableAtCurrentPage(currentPageNumber);
									}else{
										swal_Tips(data.message);
									}
								},
								error : function(request) {
									swal_Tips_Error();
								},
							});
						}
					});
					return;
				}	
			}		
			fDisPathId = row.fDisPathId;
			fStartWorkId = row.id;
			loadingCustom('正在加载中。。。');
			if(row.fIsMerge == 1){
				fIsMerge = 1;
				$.ajax({
					url : pathUrl("start/findByMergeOper.action"),
					type : "POST",
					dataType : "JSON",
					data : {
						fQty : row.fTargetQty,
						id : row.id
					},
					success : function(data) {
//						console.log(data);
						input_sum = data.length;
						$("#modal-body-id").css("height",data.length * 40 + 45);						
						if(data.length  > 0){
							//循环生产form表单
							var hl = "";
							for(var i = 0; i < data.length; i++){
								var temp = data[i];	
								hl += "<span id = 'fOperSN" + i + "'style = 'display:none;'>" + temp.fOperSN + "</span><span id = 'fMergeCode" + i + "'style = 'display:none;'>" + temp.fMergeCode + "</span>";
								hl += "<span id = 'fCardId" + i + "'style = 'display:none;'>" + temp.fCardId + "</span>";
								for(var j = 0; j < input_id.length; j++){
									hl += "<div class='col-sm-2 col-md-2 bottomContent' style='width: 12%; padding:0px 0px 3px 0px;'><span class='bottomSpan'>";								
	                                if(j == 1){
										hl += "<span class='requiredCss'>*</span>" + input_name[j] + ":";
									}else{
										hl += input_name[j] + ":";
									}
									hl += "</span>";
									var valu = temp[input_id[j]];
									if(valu == null){
										valu = 0;
									}
									if(j == 0){
										hl += "<input type='text' id='" + input_id[j] + i +"' readonly = 'true' value = '" + valu + "'";
									}else if(j == 1){//当数量为良品数的时候	
										var t = parseFloat(row.fTargetQty) - parseFloat(row.fQty);
										hl += "<input type='text' id='" + input_id[j] + i +"'value = '" + t +"'";	
									}else{
										hl += "<input type='text' id='" + input_id[j] + i +"'value = '" + valu +"'";
									}								
									hl += " name='" + input_id[j] + "' class='clean-c form-control bj_color' autocomplete='off' onkeyup= changeVal(this) onafterpaste='if(isNaN(value))execCommand(&apos;undo&apos;)'/>";															
									hl += "</div>";
								}														
							}
							$("#contentId").html(hl);
							$("#content_bottom").css("display","block");
							$('#fPassQty0').focus();//良品数输入框获得焦点							
							$("#mergeModal").modal('show');							
						}else{
							input_sum = 1;
							var hl = "";
							for(var i = 0; i < input_name.length; i++){	
								hl += "<div class='col-sm-2 col-md-2 bottomContent' style='width: 13%; padding:0px 0px 3px 0px;'><span class='bottomSpan'>";								
			                    if(i == 1){
									hl += "<span class='requiredCss'>*</span>" + input_name[i] + ":";
								}else{
									hl += input_name[i] + ":";
								}
								hl += "</span>";
								if(i == 0){
									hl += "<input type='text' id='" + input_id[i] + 0 +"' readonly = 'true'";
								}else{
									hl += "<input type='text' id='" + input_id[i] + 0 +"'";	
								}								
								hl += " name='" + input_id[i] + "' class='clean-c form-control bj_color' autocomplete='off' onkeyup='if(isNaN(value))execCommand(&apos;undo&apos;)' onafterpaste='if(isNaN(value))execCommand(&apos;undo&apos;)'/>";															
								hl += "</div>";
							}
							$("#contentId_single").html(hl);
							$("#fPassQty0").val(parseFloat(row.fTargetQty) - parseFloat(row.fQty));//给良品数赋值	
							$("#fOper0").val(row.fOper);//给良品数赋值	
							$('#fPassQty0').focus();//良品数输入框获得焦点
							$("#content_bottom_single").css("display","block");
						}
						swal.close();//关闭sweetAlert2提示框
					},
					error : function(request) {
						swal_Tips_Error();
					}
				});
			}else{
				fIsMerge = 0;
				input_sum = 1;
				var hl = "";
				for(var i = 0; i < input_namet.length; i++){	
					hl += "<div class='col-sm-2 col-md-2 bottomContent' style='width: 13%; padding:0px 0px 3px 0px;'><span class='bottomSpan'>";								
                    if(i == 1){
						hl += "<span class='requiredCss'>*</span>" + input_namet[i] + ":";
					}else{
						hl += input_namet[i] + ":";
					}
					hl += "</span>";
					if(i == 0){
						hl += "<input type='text' id='" + input_ids[i] + 0 +"' readonly = 'true'";
					}else{
						hl += "<input type='text' id='" + input_ids[i] + 0 +"'";	
					}								
    //				hl += " name='" + input_ids[i] + "' class='clean-c form-control bj_color' autocomplete='off' onkeyup='if(isNaN(value))execCommand(&apos;undo&apos;)' onafterpaste='if(isNaN(value))execCommand(&apos;undo&apos;)'/>";
					hl += " name='" + input_ids[i] + "' class='clean-c form-control bj_color' autocomplete='off'  />";
					hl += "</div>";
				}
				$("#contentId_single").html(hl);
				swal.close();//关闭sweetAlert2提示框
				$("#fPassQty0").val(parseFloat(row.fTargetQty) - parseFloat(row.fQty));//给良品数赋值	
				$("#fOper0").val(row.fOper);//给良品数赋值	
				$('#fPassQty0').focus();//良品数输入框获得焦点
				$("#content_bottom_single").css("display","block");
			}							
			$("#fWorker").val(row.fWorker);//获取操作工ID
			$("#fStartWorkId").val(row.id);//获取开工表ID
			$("#fTargetQty").val(parseFloat(row.fTargetQty) - parseFloat(row.fQty));//获取派工数
//			$("#fPassQty").val(parseFloat(row.fTargetQty) - parseFloat(row.fQty));//给良品数赋值			
//			$('#fPassQty0').focus();//良品数输入框获得焦点
		},
		onPageChange : function(number, size) {// 翻页
			if (page == number) {
				rowIndex = index;
			} else {
				$('.success').removeClass('success');
				rowIndex = "%^%%%%";
			}
		},
		onUncheck : function(index){//取消勾选
			$("#fWorker,#fStartWorkId,#fTargetQty").val("");//清空操作工ID、开工表ID、派工数
			$('#fPassQty').blur();//良品数输入框失去焦点
			$('.success').removeClass('success');
			rowIndex = "%^%%%%";
		}
	});
}

/*
 * @Description: 实现修改上一行的非良品数，下面的良品数可以自动改变
 * @param : e
 */
function changeVal(e){
	var a = e.id;	
	if(!isNaN(e.value) && e.value != ""){
		var flag = false;
		var i = 1;
		for(; i < input_id.length; i++){//确定是哪一个的id
			var index = a.indexOf(input_id[i]);
			if(index == 0){
				flag = true;
				break;
			}
		}		
		if(flag){					
			var temp = a.substr(input_id[i].length,a.length);//获得下标
			var sum = parseFloat($("#fPassQty" + temp).val()) + parseFloat($("#fOthQty" + temp).val());//当前行的良品数和次品数之和									
			for(var j = parseInt(temp) + 1; j < input_sum; j++){
				$("#fPassQty" + j).val(sum);								
			}
		}
	}	
} 
/*
 * @Description:form表单转化成json字符串
 * @param :
 */
function getInputJson(){
	var json = [];
	for(var i = 0; i < input_sum; i++){
		var params = new Object();
		var sum = 0;
		params["fTargetQty"] = $("#fTargetQty").val();
		if(input_sum == 1){
			params["fStartWorkId"] = $("#fStartWorkId").val();
		}		
		if(fIsMerge == 1){//合并工序添加fMergeCode字段
			for(var j = 0; j < input_id.length; j++){
				params[input_id[j]] = $("#" + input_id[j] + i).val();
	            if(params[input_id[j]] == ""){
	            	params[input_id[j]] = 0;
				}
				if(j > 0){
					var s = $("#" + input_id[j] + i).val();
					sum += parseFloat(s);
				}
			}
			params["fMergeCode"] = $("#fMergeCode" + i).text() ;
			params["fOperSN"] = $("#fOperSN" + i).text();
			params["fCardId"] = $("#fCardId" + i).text();
			params["fQty"] = sum;
		}
		else{
			for(var j = 0; j < input_ids.length; j++){
				params[input_ids[j]] = $("#" + input_ids[j] + i).val();
	            if(params[input_ids[j]] == ""){
	            	params[input_ids[j]] = 0;
				}
				if(j > 0){
					var s = $("#" + input_ids[j] + i).val();
					sum += parseFloat(s);
				}
			}
		}
		json.push(params);
	}
	return json;
}
$("#save_single").click(function(){
	$("#save").click();
});

/**
 * @description:"挂起"按钮点击事件
 */
$("#godown_single").click(function(){
	$("#godown").click();
});

/**
 * @description:“挂起”按钮点击事件
 */
$('#godown').click(function(){
	showLoading();
	$.ajax({
		url : pathUrl("end/suspending.action"),
		type : "POST",
		dataType : "JSON",
		data : {
			fDisId : fDisPathId,
			fStartWorkId: fStartWorkId,
		},
		success : function(data) {
			if(data.code == "0000"){
				swal_Tips_Short(data.message);
				// TODO：刷新完工记录表
				$('#finishTable').bootstrapTable('refresh');
				$("#mergeModal").modal('hide');	
				$("#contentId").html("");
				$("#content_bottom").css("display","none");	
			}else{
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
})
/*
 * @Description: 提交按钮单击事件
 * @param :
 */
$("#save").click(function() {
	var ID =  $("#fStartWorkId").val();//获取开工表ID
	var qty = parseFloat($("#fTargetQty").val());//获取派工数	
	for(var j = 0; j < input_sum; j++){
		var sum = 0;
		var gaisum =0 ;
		for(var i = 1; i < input_id.length; i++){
			/*if(i != 5){
				sum += parseFloat($("#" + input_id[i] + j).val() == "" ? 0 : $("#"+ input_id[i] + j).val());	
			}*/
			sum += parseFloat($("#" + input_id[i] + j).val() == "" ? 0 : $("#"+ input_id[i] + j).val());
		}
		for(var i = 1; i < input_idss.length; i++){
			gaisum += parseFloat($("#" + input_idss[i] + j).val() == "" ? 0 : $("#"+ input_idss[i] + j).val());
		}
		console.log(sum);
		console.log(gaisum);
		if(fIsMerge==0){
			console.log($('#fNote0').val());
			console.log(parseInt($('#fScrapNotMeQty0').val())>=1);
			if($('#fScrapNotMeQty0').val()>=1){
				if($('#fNote0').val()==null||$('#fNote0').val()==0){
					swal_Tips("已填写工废1,请填写备注");
					return false;
				}
			}
		}
		if(fIsMerge==1){
			for(var i=0;i < input_id.length; i++){
				console.log($('#fNote'+i).val());
				console.log(parseInt($('#fScrapNotMeQty'+i).val())>=1);
				if($('#fScrapNotMeQty'+i).val()>=1){
					if($('#fNote'+i).val()==null||$('#fNote'+i).val()==0){
						swal_Tips("已填写工废1,请填写备注");
						return false;
					}
				}
			}
		}
		if(isNaN(gaisum)){
			swal_Tips("请填入数字");
			return false;
		}
		if(gaisum-sum<=0){
			if(sum < 1 && j == 0){
				swal_Tips("加工数量不能为0，注：加工数量=良品数+工废数+料废数+工废1+返修数+次品数！");
				return false;
			}
		}
		if(j == 0 && fIsMerge == 0){//非合并工序
			if(qty < gaisum){
				swal_Tips("加工数量不能大于派工数量，注：加工数量=良品数+工废数+料废数+工废1+返修数+次品数！");
				return false;
			}	
		}else if(j == 0){//首道工序加工数需要和派工数量相比较
			if(qty < gaisum){
				swal_Tips("第一道工序的加工数量必须等于派工数量，注：加工数量=良品数+工废数+料废数+工废1+返修数+次品数！");
				return false;
			}	
		}else{//非首道工序加工数需要和上一道工序的良品数和次品数之和比较
			var foreGood = parseFloat($("#fPassQty" + (j - 1)).val()) + parseFloat($("#fOthQty" + (j - 1)).val());//上一道工序的良品数
			if(foreGood != gaisum){
				swal_Tips("第" + (j + 1) + "道工序的加工数量必须等于上一道工序的良品数量与次品数之和，注：加工数量=良品数+工废数+料废数+工废1+返修数+次品数！");
				return false;
			}
		}		
	}
	if(ID == ""){
		swal_Tips("请选择一条完工数据！");
		return false;
	}
	/*if(isNaN(fPassQty)){
		swal_Tips("良品数量不能为空！");
		return false;
	}
	if(fPassQty == 0){
		swal_Tips("良品数不能为0！");
		return false;
	}*/
	/*if(sum < 1){
		swal_Tips("加工数量不能为0，注：加工数量=良品数+工废数+料废数+丢失数+返修数+其他数！");
		return false;
	}
	if(qty < sum){
		swal_Tips("加工数量不能大于派工数量，注：加工数量=良品数+工废数+料废数+丢失数+返修数+其他数！");
		return false;
	}*/
	var tempDatas =  JSON.stringify(getInputJson());
	$("#mergeModal").modal('hide');
	$("#content_bottom_single").css("display","none");
	$("#contentId").html("");
	$("#contentId_single").html("");
	showLoading();
	console.log(tempDatas);
	$.ajax({
		url : pathUrl("end/mergeOperEndWork.action"),
		type : "POST",
		dataType : "JSON",
		data : {
			datas : tempDatas,
			fDisPathId : fDisPathId
		},
		success : function(data) {
			if(data.code == "0000"){
				swal_Tips_Short(data.message);
				reseting(); 
				$("#contentId").html("");
				$("#content_bottom").css("display","none");
				if(data.type=='print'){
					url=pathUrl("WR?endId="+data.id);
					window.open(url);
				}
			}else{
				swal_Tips(data.message);
			}
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
});

/*
 * @Description: 查询按钮单击事件
 * @param :
 */
$("#query").click(function() {
	wipeData();
	$("#fPassQty,#fScrapQty,#fForitemQty,#fQtyLost,#fReworkQty,#fOthQty,#fWorker,#fStartWorkId,#fTargetQty").val("");
});

/*
 * @Description: 重置按钮单击事件
 * @param :
 */
$("#reset").click(function() {
	flag = true;
	$(".clean-c").val("");
	$('#fDepId').selectpicker('refresh');
	reseting();
});

/*
 * @Description: 重置
 * @param :
 */
function reseting(){
	wipeData();
}

/*
 * @Description: 输入操作工姓名/操作工ID/派工单号回车事件
 * @param :
 */
/*$("#fWorkerF").keypress(function(event){
	if(event.keyCode == "13"){
		flag = false;
		initFinishTable();
		wipeData();
	}
});*/
/*
 * @Description: 输入操作工姓名/操作工ID/派工单号回车事件
 * @param :
 */
function wipeData(){
	var fWorker = $("#fWorkerF").val();
	if(fWorker != ""){
		$.ajax({
			url : pathUrl("emp/findByCondition.action"),
			type : 'GET',
			dataType : "JSON",
			data : {
				"row" : 100000,
				"fNumber" : fWorker
			},
			success : function(data) {
//			console.log(data)
				if(data.code == "0000"){
					if(data.rows.length == 1){
						$("#wname").val(data.rows[0].fName);
					}else{
						$("#wname").val("");
					}
				}else{
					$("#wname").val("");
//				$("#fWorker").focus();
				}
			},
			error : function(request) {
				swal_Tips_Error();
			}
		});
	}
	initFinishTable();
	$('.success').removeClass('success');
	rowIndex = "%^%%%%";
}

/*
 * @Description: 初始化工作中心下拉框里的数据
 * @param : 
 */
function pullDown(){
	$.ajax({
		url : pathUrl("workCenter/getworkCenterIdAndName.action"),
		type : 'GET',
		dataType : "JSON",
		success : function(data) {
			var option = "";
			$("#fDepId").empty();
			option = '<option value="">' + "请选择" + '</option>';
			for (x in data) {
				option += '<option value="' + data[x].text + '">' + data[x].value + '</option>';
			}
			$("#fDepId").html(option);
			$('#fDepId').selectpicker('refresh');
		},
		error : function(request) {
			swal_Tips_Error();
		}
	});
}
/*
 * @Description: 操作工卡号按按退格或delete事件
 * @param :
 */
$("#fWorkerF").keydown(function(event){
	if(event.keyCode == "8" || event.keyCode == "46"){
		$("#wname").val("");
	}
});
/*
 * @Description: 查询条件按回车事件
 * @param :
 */
$("#fBillNo,#fCode,#fWorkerF").keypress(function(event){
	if(event.keyCode == "13"){
		if($("#fWorkerF").val() != ""){
			wipeData();
		}
		initFinishTable();
	}
});